package service

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/util/gconv"
	"tFilm4/internal/model"
	"tFilm4/internal/service/internal/dao"
	"tFilm4/internal/service/internal/do"
)

type sMovieOrder struct{}

var insMovieOrder = sMovieOrder{}

func MovieOrder() *sMovieOrder {
	return &insMovieOrder
}

func (s *sMovieOrder) CreateMovieOrder(ctx context.Context, in model.CreateMovieOrderInput) (err error) {
	return dao.MovieOrder.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		_, err := dao.MovieOrder.Ctx(ctx).Data(do.MovieOrder{
			UserId:      in.UserId,
			SessionId:   in.SessionId,
			MovieName:   in.MovieName,
			MovieImage: in.MovieImage,
			TotalPrice:  in.TotalPrice,
			SelectTable: in.SelectTable,
		}).Insert()
		sessionInfo, err := MovieSession().GetSessionById(ctx, in.SessionId)
		j, err := gjson.DecodeToJson(in.SelectTable)
		arr := j.Array()
		table := []byte(sessionInfo.SeatTable.Table)
		for i := 0; i < len(arr); i++ {
			m := gconv.Map(arr[i])
			row := gconv.Int(m["row"])
			col := gconv.Int(m["col"])
			table[((row-1)*sessionInfo.SeatTable.Cols)+col-1] = '2'
		}
		_, err = dao.SeatTable.Ctx(ctx).Data(do.SeatTable{
			Table:      table,
			EmptyCount: sessionInfo.SeatTable.TotalCount - len(arr),
		}).Where("table_id", sessionInfo.SeatTable.TableId).Update()
		return err
	})
}

func (s *sMovieOrder) GetMovieOrderByUserId(ctx context.Context, userId int64) (count int, infos []model.OrderInfo, err error) {
	err = dao.MovieOrder.Ctx(ctx).Where("user_id", userId).OrderDesc("create_at").ScanList(&infos, "MovieOrder")
	if err != nil {
		return
	}
	err = dao.User.Ctx(ctx).Where("user_id", gdb.ListItemValuesUnique(&infos, "MovieOrder", "UserId")).ScanList(&infos, "User", "MovieOrder", "user_id:UserId")
	if err != nil {
		return
	}
	err = dao.MovieSession.Ctx(ctx).Where("session_id", gdb.ListItemValuesUnique(&infos, "MovieOrder", "SessionId")).ScanList(&infos, "MovieSession", "MovieOrder", "session_id:SessionId")
	if err != nil {
		return
	}
	count, err = dao.MovieOrder.Ctx(ctx).Where("user_id", userId).Count()
	return
}
func (s *sMovieOrder) GetMovieOrderById(ctx context.Context, orderId int64) (info model.OrderInfo, err error) {
	var infos []model.OrderInfo
	err = dao.MovieOrder.Ctx(ctx).Where("id", orderId).OrderDesc("create_at").ScanList(&infos, "MovieOrder")
	if err != nil {
		return
	}
	err = dao.User.Ctx(ctx).Where("user_id", gdb.ListItemValuesUnique(&infos, "MovieOrder", "UserId")).ScanList(&infos, "User", "MovieOrder", "user_id:UserId")
	if err != nil {
		return
	}
	err = dao.MovieSession.Ctx(ctx).Where("session_id", gdb.ListItemValuesUnique(&infos, "MovieOrder", "SessionId")).ScanList(&infos, "MovieSession", "MovieOrder", "session_id:SessionId")
	if err != nil {
		return
	}
	info = infos[0]
	return
}